/* —————————————— 网络请求 ———————————————— */
/*
 * 异步请求封装，提供get、post的异步函数 upload请求
 */
//请求返回参数
import config from "@/common/config";
let httpServe = (resolve, res) =>{
    if (res.statusCode == 200) {
        resolve(res.data);
    } else {
        const pages = getCurrentPages();
        const showToastOptions = {
            title: res.data.msg || '获取数据失败',
            icon: 'none',
            duration: 2000,
            mask: true,
            success() {
                if (res.statusCode === 401 || res.statusCode === 403) {
                    if (pages.length > 0) {
                        const currentPage = pages[pages.length - 1];
                        let pageUrl = `/${currentPage.route}`;
                        if (pageUrl !== '/pages/login/login') {
                            setTimeout(() => {
                                if(config.AUTHORISATION_ENABLE){
                                    uni.reLaunch({
                                        url: '/pages/login/web-login'
                                    })
                                }else{
                                    uni.reLaunch({
                                        url: '/pages/login/login'
                                    })
                                }
                            }, 2000);
                        }
                    }
                }
            }
        };

        switch (res.statusCode) {
            case 401:
                if (res.data.code == 6000) {
                    uni.setStorageSync('loginName', '');
                    uni.setStorageSync('loginPwd', '');
                } else {
                    let loginName = uni.getStorageSync('loginName');
                    let loginPwd = uni.getStorageSync('loginPwd');
                    showToastOptions.title= loginName && loginPwd ? '正在登录中，请稍后...' : '未认证或认证已过期，请重新登录';
                }
                break;
            case 403:
                if (res.data.msg === '未在服务期间，请联系运营人员') {
                    uni.setStorageSync('loginName', '');
                    uni.setStorageSync('loginPwd', '');
                }
                break;
            case 500:
                // resolve(res.data);
                break;
            default:
                break;
        }

        uni.showToast(showToastOptions);
    }
}
// HTTP: GET/POST封装
let http = {
    // Loading METHOD
    initload() {
        uni.showLoading({
            title: '加载中',
            mask: true,
        })
    },

    // HEADER 请求头配置
    handleHeader(type, grant_type, login) {
        let headers = {};
        if (type === 'HEADER_JSON') {
            headers['Content-Type'] = 'application/json;charset=utf-8';
        } else if (type === 'HEADER_XWWW') {
            headers['Content-Type'] = 'application/x-www-form-urlencoded';
        } else if (type === 'FORM_DATA') {
            headers['Content-Type'] = 'multipart/form-data';
        }

        if(grant_type) {
            headers['grant_type'] = grant_type;
        }
        headers['wx'] = true;

        if (login) {
            // header注入token
            headers['Authorization'] = 'Basic amtyX2FkbWluX2NsaWVudDoxMjM0NTY=';
        } else {
            if (uni.getStorageSync("token")) {
                headers['Authorization'] = uni.getStorageSync("token");
            } else {
                headers['Authorization'] = '';
            }
        }
        return headers;
    },
    /**
     * post方法，
     * @param url {String} [请求的url地址]
     * @param param {Object} [请求携带的参数]
     * @param loading {Boolean} [请求弹窗]
     * @param type {String} [请求头content-type参数]
     * @param grant_type {String} [请求头grant_type参数]
     * @param login {Boolean} [是否登录存入请求头]
     **/
    get: function (url, param, loading = true, type = 'HEADER_XWWW', grant_type = '', login = false) {
        if (loading) this.initload(); // loading加载中
		let header = this.handleHeader(type, grant_type, login)
        if (!url) return 0; // url为空关闭函数
        return new Promise(function (resolve, reject) {
            uni.request({
                url: url,
                data: param || {},
                header: header,
                method: "GET",
                success: (res) => {
                    if(loading) uni.hideLoading();
                    httpServe(resolve, res)
                },
                fail: (err) => {
                    if(loading) uni.hideLoading();
                    uni.showToast({
                        title: '网络错误',
                        duration: 2000, icon: 'error'
                    });
                    reject(err);
                },
                complete: (res) => {
                }
            });
        });
    },
    /**
     * post方法，
     * @param url {String} [请求的url地址]
     * @param param {Object} [请求携带的参数]
     * @param loading {Boolean} [请求弹窗]
     * @param type {String} [请求头content-type参数]
     * @param grant_type {String} [请求头grant_type参数]
     * @param login {Boolean} [是否登录存入请求头]
     **/
    post: function (url, param, loading = true, type = 'HEADER_JSON', grant_type = '', login = false) {
        if (loading) this.initload();
		let header = this.handleHeader(type, grant_type, login)
        if (!url) return 0;
        return new Promise(function (resolve, reject) {
            uni.request({
                url: url,
                data: param || {},
				header: header,
                method: "POST",
                success: (res) => {
                    if(loading) uni.hideLoading();
                    httpServe(resolve, res)
                },
                fail: (err) => {
                    if(loading) uni.hideLoading();
                    uni.showToast({
                        title: '网络错误',
                        duration: 2000, icon: 'error'
                    });
                    reject(err);
                },
                complete: (res) => {

                }
            });
        });
    },
    /**
     * upload方法，
     * @param url {String}[请求的url地址]
     * @param formData {Object}[请求携带的参数]
     * @param filePath {String}[请求图片路径]
     * @param loading {Boolean}[请求弹窗]
     * @param type {String}[请求头content-type参数]
     * @param grant_type {String}[请求头grant_type参数]
     * @param login {Boolean}[是否登录存入请求头]
     **/
    upload: function (url, formData,filePath, loading, type = 'HEADER_XWWW', grant_type = '', login = false) {
        if (loading) this.initload();
		let header = this.handleHeader(type, grant_type, login)
        if (!url) return 0;
        return new Promise(function (resolve,reject){
            uni.uploadFile({
                url: url,
                name: 'file',
                header: header,
                formData: formData,
                filePath:filePath,
                success: (res) => {
                    if(loading) uni.hideLoading();
                    httpServe(resolve, res);
                },
                fail: (err) => {
                    if(loading) uni.hideLoading();
                    uni.showToast({
                        title: '网络错误',
                        duration: 2000, icon: 'error'
                    });
                    reject(err);
                },
                complete: (res) => {
                }
            })
        })
    },
    asyncPost: function (url, param, loading,type = 'HEADER_JSON', grant_type = '', login = false) {
        return new Promise((resolve, reject) => {
            this.post(url, param, loading,type, grant_type, login).then(res => {
                resolve(res)
            });
        });
    },
    asyncGet: function (url, param, loading,type = 'HEADER_JSON', grant_type = '', login = false) {
        return new Promise((resolve, reject) => {
            this.get(url, param, loading,type, grant_type, login).then(res => {
                resolve(res);
            });
        });
    },

};

export default http;